import 'dart:convert';
import 'dart:io';

import 'package:demo/model/constant_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../model/contact_model.dart';
import '../../../model/identity_model.dart';
import '../../../model/file_model.dart' as FileBean;
import '../../../model/key_value_model.dart';
import '../../../net/api_provider.dart';
import '../../global.dart';
import '../../routes/app_pages.dart';
import '../../widgets/dialog_face_agreement.dart';
import '../../widgets/dialog_key_value.dart';

class ApplyController extends GetxController with WidgetsBindingObserver {

  var platform = const MethodChannel("sing.top/rth");

  var moneyStr = '';
  var isAuthID = false.obs; // 身份证是否已认证
  var isAuthBase = false.obs; // 基本信息是否已认证
  var isAuditing = false.obs; // 是否在审核
  var name = ''; // 身份证姓名
  var identityNum = ''; // 身份证号
  final FocusNode focusNode = FocusNode();
  ApiProvider apiProvider = Get.put(ApiProvider());

  Map<String, dynamic>? timeList; // 借款期限
  Rx<KeyValue> selectTime = KeyValue(0,'').obs; /// 选择的借款期限
  Map<String, dynamic>? useList; // 借款用途
  Rx<KeyValue> selectUse = KeyValue(0,'').obs; /// 选择的借款用途

  @override
  void onInit() {
    super.onInit();
    WidgetsBinding.instance.addObserver(this);
    isAuditing.value = Global.isAuditing;
  }

  @override
  void onReady() {
    super.onReady();
    platform.setMethodCallHandler(flutterMethod);
    initAuth();
    getConstant();
  }

  @override
  void onClose() {
    super.onClose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if(state == AppLifecycleState.resumed){
      initAuth();
    }
  }

  Future<dynamic> flutterMethod(MethodCall methodCall) async {
    switch (methodCall.method) {
      case 'faceOk':
        Map<dynamic, dynamic> data = methodCall.arguments; // 接收来自原生代码的数据
        uploadImg(data['dec_image'],data['score']);
        break;
      case 'faceError':
        Map<dynamic, dynamic> data = methodCall.arguments; // 接收来自原生代码的数据
        Get.toNamed(Routes.FACE_ERROR,arguments: data);
        break;
    }
  }

  /// 是否完成认证
  void initAuth() async{
    var result1 = await apiProvider.getData({}, ApiProvider.identity);
    if(result1.code == 200){
      var identity = Identity.fromJson(result1.data);
      if(identity.identityNum != null && identity.identityNum!.isNotEmpty && identity.realName != null && identity.realName!.isNotEmpty){
        isAuthID.value = true;
        name = identity.realName!;
        identityNum = identity.identityNum!;
      }
    }

    var result2 = await apiProvider.getData({}, ApiProvider.contact_detail);
    if(result2.code == 200){
      var contact = Contact.fromJson(result2.data);
      if(contact.secondPhone!.isNotEmpty){
        isAuthBase.value = true;
      }
    }
  }

  void hintKeyboard(){
    focusNode.unfocus(); // 触发焦点变化，键盘收回
  }

  // 上传图片
  void uploadImg(String dec_image,String score) async{
    final Uint8List data = base64Decode(dec_image);

    final currentTime = DateTime.now();
    int timestamp = currentTime.millisecondsSinceEpoch;
    // 创建临时文件
    final tempDir = await getTemporaryDirectory();
    final filePath = '${tempDir.path}/$timestamp.png';
    final file = File(filePath);
    // 将数据写入文件
    await file.writeAsBytes(data);

    var result = await apiProvider.uploadFaceImg(file);
    if(result.code == 200){
      var file = FileBean.File.fromJson(result.data);
      var r = await apiProvider.getData({'face_image':file.url},ApiProvider.updated_identity);
      if(r.code == 200){
        Get.offNamed(Routes.CONFIRM,parameters : {'loan_amount':moneyStr,'loan_period_id':'${selectTime.value.key}','loan_type':'${selectUse.value.key}'});
      }else{
        EasyLoading.showToast('${result.msg}');
      }
    }else{
      EasyLoading.showToast('${result.msg}');
    }
  }

  // 身份证认证
  void toIdAuth(){
    hintKeyboard();
    if(isAuthID.value){
      EasyLoading.showToast('已完成实名认证');
    }else{
      Get.toNamed(Routes.ID_INFO);
    }
  }

  // 基本信息认证
  void toBaseAuth(){
    hintKeyboard();
    if(!isAuthID.value){
      EasyLoading.showToast('请先完成实名认证');
    }else{
      Get.toNamed(Routes.BASE_INFO);
    }
  }

  void getConstant() async{
    var result = await apiProvider.getData({}, ApiProvider.constant);
    if(result.code == 200){
      var constant = Constant.fromJson(result.data);
      timeList = constant.timeList;
      useList = constant.useList;
    }else{
      EasyLoading.showToast('${result.msg}');
    }
  }

  /// 选择借款期限
  void chooseTime(){
    hintKeyboard();
    if(timeList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(timeList, (code,value){
        selectTime.value = KeyValue(int.tryParse(code) ?? 0,value);
      }),
    );
  }

  /// 选择借款用途
  void chooseUse(){
    hintKeyboard();
    if(useList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(useList, (code,value){
        selectUse.value = KeyValue(int.tryParse(code) ?? 0,value);
      }),
    );
  }

  // 点击申请
  void clickApply(){
    if(moneyStr.isEmpty){
      EasyLoading.showToast('请输入借款金额');
    }else{
      try {
        int num = int.parse(moneyStr);
        if(num % 1000 == 0){
          if(selectTime.value.key == 0 || selectTime.value.value.isEmpty){
            EasyLoading.showToast('请选择借款期限');
          }else if (selectUse.value.key == 0 || selectUse.value.value.isEmpty){
            EasyLoading.showToast('请选择借款用途');
          }else if(isAuthID.isFalse){
            EasyLoading.showToast('请完成身份证认证');
          }else if(isAuthBase.isFalse){
            EasyLoading.showToast('请完成基本信息认证');
          }else{
            showDialog();
          }
        }else{
          EasyLoading.showToast('借款金额需为1000的整数倍');
        }
      } catch (e) {
        EasyLoading.showToast('借款金额需为1000的整数倍');
      }
    }
  }

  // 人脸弹窗
  void showDialog(){
    Get.bottomSheet(
      DialogFaceAgreement(() => requestPermission()),
      isDismissible: true,
    );
  }

  void requestPermission() async{
    if(GetPlatform.isAndroid){
        // 请求存储权限
        final permissionState = await getStoragePermission();
        if (permissionState) {
          platform.invokeMethod('toFace',{ 'name':name ,'identityNum':identityNum});
          Get.back(); // 关闭弹窗
        } else {
          EasyLoading.showToast('请开启相关权限后继续');
          openAppSettings();
        }
    } else if(GetPlatform.isIOS){
      // 请求权限
      Map<Permission, PermissionStatus> statuses = await [
        Permission.camera,
        Permission.photos,
      ].request();

      // 检查权限状态
      PermissionStatus? locationStatus1 = statuses[Permission.camera];
      PermissionStatus? locationStatus2 = statuses[Permission.photos];
      if (locationStatus1 == PermissionStatus.granted && locationStatus2 == PermissionStatus.granted) {// 权限被授予
        platform.invokeMethod('toFace',{ 'name':name ,'identityNum':identityNum});
        Get.back(); // 关闭弹窗
      // } else if (locationStatus == PermissionStatus.denied) {// 权限被拒绝
      //   EasyLoading.showToast('请开启相关权限后继续');
      // } else if (locationStatus == PermissionStatus.neverAskAgain) { // 用户选择不再提示，需引导用户去设置中开启
      } else  {
        EasyLoading.showToast('请开启相关权限后继续');
      }
    }else{
      EasyLoading.showToast('暂不支持该设备');
    }
  }

  /// 获取存储权限
  Future<bool> getStoragePermission() async {
    late PermissionStatus myPermission1;
    late PermissionStatus myPermission2;

    if(GetPlatform.isAndroid){
      myPermission1 = await Permission.camera.request();
      myPermission2 = await Permission.microphone.request();
    }
    if (myPermission1 != PermissionStatus.granted || myPermission2 != PermissionStatus.granted) {
      return false;
    } else {
      return true;
    }
  }

}
